package com.tstudy.laoshibang.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpHost;
import org.json.JSONException;
import org.json.JSONObject;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.HttpManager.LoadImageViewResponse;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.share.WrapQQ;
import com.tstudy.laoshibang.share.WrapSinaWeibo;
import com.tstudy.laoshibang.share.WrapWechat;
import com.umeng.analytics.MobclickAgent;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

@SuppressWarnings("deprecation")
@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class CommonUtil {
	private static final Uri STORAGE_URI = Images.Media.EXTERNAL_CONTENT_URI;
	private static final String IMAGE_MIME_TYPE = "image/png";
	private static final String DEFAULT_DATE_PATTEN = "yyyy-MM-dd HH:mm:ss";
	public static final String PROMOTION_PARAM_DATE_PATTEN = "yyyy-MM-dd HH:mm";
	public static String PROMOTION_DISPLAY_DATE_PATTEN = "yyyy年MM月dd日  HH:mm";
	public static String mDatePatten = "yyyy年MM月dd日";
	public static final String RESERVE_TIME_DISPLAY_PATTEN = "yyyy-MM-dd HH:mm";
	
	public static String getDateStr(Calendar calendar,String pattern){
		return getDateStr(calendar.getTime(), pattern);
	}
	public static String getDateStr(Calendar date){
		return getDateStr(date.getTime(),DEFAULT_DATE_PATTEN);
	}
	
	
	public static String getDateStr(Date date){
		return getDateStr(date,DEFAULT_DATE_PATTEN);
	}
	
	public static Date parseDate(String str){
		return parseDate(str, DEFAULT_DATE_PATTEN);
	}
	
	
	public static String getDateStr(Date date,String pattern){
		if(date == null || TextUtils.isEmpty(pattern)){
			return null;
		}
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}
	
	public static Date parseDate(String str,String pattern){
		if(TextUtils.isEmpty(str) || TextUtils.isEmpty(pattern)){
			return null;
		}
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		try {
			return df.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 时间显示转换
	 * 一分钟内显示刚刚
	 * 一小时前显示多少分钟前
	 * 一天内显示多少小时前
	 * 一周内显示星期几
	 * 大于一周显示yy年MM月dd日
	 * @param date
	 * @return
	 */
	public static String timelineDateStr(long createTime) {
		long minute = 60*1000;
		long hour = 60*minute;
		long day = 24*hour;
		long week = 7*day;
		Calendar currentDate = Calendar.getInstance();
		int currentDay = currentDate.get(Calendar.DAY_OF_MONTH);
		Calendar createDate = Calendar.getInstance();
		createDate.setTimeInMillis(createTime);
		int createDay = createDate.get(Calendar.DAY_OF_MONTH);
		long currentTime = currentDate.getTimeInMillis();
		long distance = currentTime-createTime;
		if (distance < minute) {
			return "刚刚";
		}else if (distance < hour){
			long distanceMin = distance/minute;
			return distanceMin + "分钟前";
		}else if (distance < day){
			if (currentDay == createDay) {
				long distanceHour = distance/hour;
				return distanceHour + "小时前";
			}else{
				return "1天前";
			}
		}else if (distance < week){
			int result = 1;
			int createMohth = createDate.get(Calendar.MONTH);
			int currentMonth = currentDate.get(Calendar.MONTH);
			if (currentMonth > createMohth) {//跨月
				int createYear = createDate.get(Calendar.YEAR);
				int currentYear = currentDate.get(Calendar.YEAR);
				if (currentYear > createYear) {//跨年
					result = 31-createDay + currentDay;
					
				}else{
					result = getDayCount(createYear, createMohth)-createDay + currentDay;
				}
				return result + "天前";
			}else{
				result = currentDay-createDay;
			}
			return result + "天前";
		}else{
			return getDateStr(createDate,mDatePatten);
		}
		
	}
	
	public static String couponEndDate(long createTime) {
		createTime *=1000;
		Calendar createDate = Calendar.getInstance();
		createDate.setTimeInMillis(createTime);
		return getDateStr(createDate,"MM-dd");
	}
	
	
	
	/**
	 * 根据手机的分辨率�?dp 的单�?转成�?px(像素)
	 */
	public static int dip2px(float dpValue) {
		return Math.round(dpValue * BaseApplication.mDensity);
	}

	/**
	 * 根据手机的分辨率�?px(像素) 的单�?转成�?dp
	 */
	public static int px2dip(float pxValue) {
		return (int) Math.round(pxValue / BaseApplication.mDensity);
	}

	/**
	 * 试着获取本机号码
	 * 
	 * @return
	 */
	public static String getPhoneNumble() {
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager) BaseApplication.mContext.getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getLine1Number();
	}

	public static double getArcPosX(double degree, int radius) {
		return radius * Math.cos(Math.PI * degree / 180);
	}

	public static double getArcPosY(double degree, int radius) {
		return radius * Math.sin(Math.PI * degree / 180);
	}
	
	/**
	 * MD5 Encrypt
	 * @param val
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String getMD5(String val) {
		return getString(getMD5Byte(val));
	}

	public static byte[] getMD5Byte(String val) {
		byte[] m = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(val.getBytes());
			m= md5.digest();// 加密
		} catch (Exception e) {
		}
		return m;
	}
	
	public static String toHexString(byte[] array){
		StringBuffer output = new StringBuffer();
		for (int i = 0; i < array.length; i++) {
			output.append("%02x");
			output.append(array[i]);
		}
		return output.toString();
	}
	
	private static String getString(byte[] b) {
//		StringBuffer sb = new StringBuffer();
//		for (int i = 0; i < b.length; i++) {
//			sb.append(b[i]);
//		}
//		return sb.toString();
		int i; 
		StringBuffer buf = new StringBuffer(""); 
		for (int offset = 0; offset < b.length; offset++) { 
			i = b[offset]; 
			if(i<0) i+= 256; 
			if(i<16) 
			buf.append("0"); 
			buf.append(Integer.toHexString(i)); 
		} 
		return buf.toString();
		
	}
	
	static public String convertDistanceToString(double distance) {
		if (distance >= 0) {
			if (distance < 1000) {
				return String.format("%.0f m", distance);
			} else if (distance < 100000) {
				return String.format("%.2f km", distance / 1000);
			} else {
				return String.format("%.0f km", distance / 1000);
			}
		}
		return "--";
	}
	// Get round corner bitmap.
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getWidth());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}
	
	public static Bitmap getCircleBitmapWithBorder(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xffffffff;
		final Paint paint = new Paint();
		int srcW = bitmap.getWidth();
		int srcH = bitmap.getHeight();
		int desW = Math.min(srcW, srcH);
		final float roundPx = desW/2;
		final Rect src = new Rect(0, 0, srcW, srcH);
		Rect des = null;
		if (srcW > srcH) {
			int left = (srcW-desW)/2;
			des = new Rect(left , 0, left+desW, srcH);
		}else{
			int top = (srcH-desW)/2;
			des = new Rect(0 , top, srcW, top+desW);
		}
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawCircle(srcW/2,srcH/2,roundPx, paint);//图片中心点画�?
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		final Paint imagePaint = new Paint();
		imagePaint.setColor(0xffffffff);
		canvas.drawBitmap(bitmap, src, des, paint);
		return output;
	}
	// Get round corner bitmap.
		public static Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
			Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas(output);
			final int color = 0xff424242;
			final Paint paint = new Paint();
			int srcW = bitmap.getWidth();
			int srcH = bitmap.getHeight();
			int desW = Math.min(srcW, srcH);
			final float roundPx = desW/2;
			final Rect src = new Rect(0, 0, srcW, srcH);
			Rect des = null;
			if (srcW > srcH) {
				int left = (srcW-desW)/2;
				des = new Rect(left , 0, left+desW, srcH);
			}else{
				int top = (srcH-desW)/2;
				des = new Rect(0 , top, srcW, top+desW);
			}
			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(color);
			canvas.drawCircle(srcW/2,srcH/2,roundPx, paint);//图片中心点画�?
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitmap, src, des, paint);
			return output;
		}
		
		
//	public static  void galleryAddPic(String fileName) {
//		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//		File f = new File(fileName);
//		Uri contentUri = Uri.fromFile(f);
//		mediaScanIntent.setData(contentUri);
//		BaseApplication.mContext.sendBroadcast(mediaScanIntent);
//	}	
	public static String saveImageToGallery(Context context, Bitmap bmp) {
	    // 首先保存图片
	    String fileName = System.currentTimeMillis() + ".jpg";
	    File file = new File(getUploadPicturePath(), fileName);
	    try {
	        FileOutputStream fos = new FileOutputStream(file);
	        bmp.compress(CompressFormat.JPEG, 100, fos);
	        fos.flush();
	        fos.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
		}
	    
	    // 其次把文件插入到系统图库
	    try {
	        MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), fileName, null);
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    }
	    // 最后通知图库更新
	    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
	    return file.getAbsolutePath();
	}
	
	public static int getAlbumOrientation(Uri photoUri) {
	    /* it's on the external media. */
	    Cursor cursor = BaseApplication.mCurrentActivity.getContentResolver().query(photoUri,
	            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
	    if (cursor.getCount() != 1) {
	        return -1;
	    }
	    cursor.moveToFirst();
	    return cursor.getInt(0);
	}
	
	/**
	 * For the camera album images process, in look and profile portrait.
	 */
	public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}
	
	/**
	 * Decode
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static Bitmap setCustomPicFromData (byte[] bytes) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		// 这个isjustdecodebounds很重�?
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);
		// 获取到这个图片的原始宽度和高�?
		int picWidth = opt.outWidth;
		int picHeight = opt.outHeight;

		// 获取目标图的宽度和高�?
		int screenWidth = BaseApplication.mScreenWidth;
		int screenHeight = BaseApplication.mScreenHeight;
		// isSampleSize是表示对图片的缩放程度，比如值为2图片的宽度和高度都变为以前的1/2
		opt.inSampleSize = 1;
		// 根据屏的大小和图片大小计算出缩放比例
		if (picWidth > picHeight) {
			if (picWidth > screenWidth)
				opt.inSampleSize = picWidth / screenWidth;
		} else {
			if (picHeight > screenHeight)

				opt.inSampleSize = picHeight / screenHeight;
		}
		// 这次再真正地生成�?��有像素的，经过缩放了的bitmap
		opt.inJustDecodeBounds = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt);
		return bm;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		outStream = null;
		return data;
	}
	
	/**
	 * 首先判断当前是横拍还是竖拍，然后在调用相机拍照后，在保存图片的方法里，进行竖拍的照片90度旋�? Configuration config =
	 * getResources().getConfiguration(); if (config.orientation==1)
	 * 坚拍横拍，还是横拍转竖拍，都要先在surfaceChanged方法，停止预览相机，重新设置下摄像头就不会再出现90度旋转�?
	 * width:1632...height:1224
	 */
	public static Bitmap rotateBitmap(Bitmap bitmapOrg, int degree) {
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 缩放图片动作
		// matrix.postScale(scaleWidth, scaleHeight);
		// 旋转图片 动作
		matrix.postRotate(degree);
		// 创建新的图片
		Bitmap resizedBitmap = null;
		try {
			resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight(), matrix,
					true);
		} catch (OutOfMemoryError e) {
			while (resizedBitmap == null) {
				System.gc();
				System.runFinalization();
				resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight(),
						matrix, true);
			}
		}
		return resizedBitmap;
	}
	
	/**
	 * recycle bitmap
	 */
	static public void recycleBm(Bitmap myBitmap) {
		if (myBitmap != null && !myBitmap.isRecycled()) {
			myBitmap.recycle();
			myBitmap = null;
			System.gc();
			Runtime.getRuntime().gc();
		}
	}

	static final int MINUTES_ONE_DAY = 60 * 24;
	static final int MINUTES_ONE_HOUR = 60;

	static public String getRelativeTime(String timeStr) {
		// String time = "2012-12-08 13:39:57 +0000";
		// SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(time);
		String rtStr = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date createDate = null;
		Date currentDate = null;
		Calendar cal = Calendar.getInstance();
		try {
			createDate = sdf.parse(timeStr);
			currentDate = sdf.parse(sdf.format(cal.getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int diffInMins = (int) ((currentDate.getTime() - createDate.getTime()) / (1000 * 60));
		if (diffInMins >= MINUTES_ONE_DAY) {
			rtStr = String.format("%d d", diffInMins / MINUTES_ONE_DAY);
		} else if (diffInMins >= MINUTES_ONE_HOUR) {
			rtStr = String.format("%d h", diffInMins / MINUTES_ONE_HOUR);
		} else {
			rtStr = String.format("%d m", diffInMins);
		}
		LogUtil.d("--rtStr==" +  rtStr);
		return rtStr;
	}

	/**
	 * reflect String to integer
	 * 
	 * @param myClass
	 * @param fieldStr
	 * @return
	 */
	static public int reflectString2Int(Class<?> myClass, String fieldStr) {
		Field currentF = null;
		int index = -1;
		try {
			currentF = myClass.getField(fieldStr);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		Class<?> t = null;
		try {
			t = currentF.getType();
			if (t == int.class) {
				index = currentF.getInt(null);
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return index;
	}

	static public boolean checkDeviceChinese() {
		String lang = BaseApplication.mCurrentActivity.getResources().getConfiguration().locale.getCountry();
		return lang.equals("CN");
		// Set Chinese
		/*
		 * Configuration config =
		 * IspiedApplication.mCurrentActivity.getResources().getConfiguration(); DisplayMetrics dm
		 * = IspiedApplication.mCurrentActivity.getResources() .getDisplayMetrics(); config.locale
		 * = Locale.SIMPLIFIED_CHINESE;
		 * IspiedApplication.mCurrentActivity.getResources().updateConfiguration(config, dm);
		 */
	}

	static public void checkDeviceCode() {
		String defaultCharsetName = Charset.defaultCharset().displayName();
		LogUtil.d("defaultCharsetName:" + defaultCharsetName);
	}
	
	public static boolean hasSdCard() {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // �?��sd是否可用
			LogUtil.d("SD card is not avaiable/writeable right now.");
			return false;
		}
		return true;
	}

	public static String getSdCardPath() {
		String sdPath = "";
		if (hasSdCard()) {
			sdPath = Environment.getExternalStorageDirectory().toString();
			LogUtil.d( "--sdPath==" + sdPath);
		}
		return sdPath;
	}
	
	/**
	 * 获取网络连接状�?
	 * 
	 * @return
	 */
	public static int getNetWorkType() {
		ConnectivityManager connectivityManager = (ConnectivityManager) BaseApplication.mContext
				.getSystemService(BaseApplication.CONNECTIVITY_SERVICE);
		NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (mobile != null && !mobile.isConnected() && wifi != null && !wifi.isConnected()) {
			return CONSTANT.NETWORK_TYPE_NONETWORK;
		}
		if (!wifi.isConnected() && mobile.isConnected()) {
			if (getProxyHttpHost() != null) {
				return CONSTANT.NETWORK_TYPE_WAP;
			} else {
				return CONSTANT.NETWORK_TYPE_MOBILE;
			}
		}
		return CONSTANT.NETWORK_TYPE_WIFI;
	}

	/**
	 * 根据手机上网是否设置代理（wap方式接入�?
	 * 
	 * @param context
	 * @return
	 */
	static public HttpHost getProxyHttpHost() {
		ConnectivityManager ConnMgr = (ConnectivityManager) BaseApplication.mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = ConnMgr.getActiveNetworkInfo();
		String proxyHost = null;
		int proxyPort = 0;
		if (info != null) {
			if (info.getType() != ConnectivityManager.TYPE_WIFI) {
				// GPRS: APN http proxy
				proxyHost = android.net.Proxy.getDefaultHost();
				proxyPort = android.net.Proxy.getDefaultPort();
			}
		}
		if (proxyHost != null) {
			return new HttpHost(proxyHost, proxyPort);
		} else {
			return null;
		}
	}
	
	/**
	 * 获取上传图片的存储路�?
	 * @return
	 */
	public static String getUploadSpotPath(){
		String path = null;
		if (hasSdCard()) {
			path = BaseApplication.mContext.getExternalFilesDir("").toString();
		}else{
			path = BaseApplication.mContext.getFilesDir().toString();
		}
		path += "/uploadImage/";
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		return path;
	}
	
	/**
	 * 获取拍照图片的存储路�?
	 * @return
	 */
	public static String getTakePhotoSavePath(){
		String path = null;
		if (hasSdCard()) {
			path = BaseApplication.mContext.getExternalFilesDir("").toString();
		}else{
			path = BaseApplication.mContext.getFilesDir().toString();
		}
		path += "/ispied/";
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		return path;
	}
	
	/**
	 * �?��体库里写入数�?
	 * 
	 * @param context
	 * @param path
	 */
	public static void inserMideaLibrary(Context context, String path) {
		ContentResolver contentResolver = context.getContentResolver();
		ContentValues values = new ContentValues(7);
		values.put(Images.Media.TITLE, "Weico+");
		values.put(Images.Media.MIME_TYPE, IMAGE_MIME_TYPE);
		values.put(Images.Media.DATA, path);
		contentResolver.insert(STORAGE_URI, values);
	}
	
	public static String saveImage(String path,Bitmap bitmap){
		File file = null;
		FileOutputStream output = null;
		try {
			file = new File(path,System.currentTimeMillis()+ ".jpg");
			output = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG,80,output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file != null ? file.toString():null;
	}
	
	public static String saveLogoImagePath(){
		File file = null;
		FileOutputStream output = null;
		String path = getUploadSpotPath();
		try {
			Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.mContext.getResources(),R.drawable.logo);
			file = new File(path,"logo.png");
			output = new FileOutputStream(file);
			bitmap.compress(CompressFormat.PNG,80,output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file != null ? file.toString():null;
	}
	
	public static String getLogoImagePath(){
		File file = new File(getUploadSpotPath()+ "logo.png");
		if (file.exists()) {
			return file.toString();
		}
		return null;
	}
	
	/** 计算string的长�?�?��中文算两个字�?*/
	public static int getStrLength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		int length = value.length();
		String temp = null;
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度�?，否则为1 */
		for (int i = 0; i < length; i++) {
			/* 获取�?��字符 */
			 temp = value.substring(i, i + 1);
			/* 判断是否为中文字�?*/
			if (temp.matches(chinese)) {
				/* 中文字符长度�? */
				valueLength += 2;
			} else {
				/* 其他字符长度�? */
				valueLength += 1;
			}
		}
		return valueLength;
	}
	
	/**
	 * 备注：将字符编码GBK改为UTF-8，则每个中文长度按3个字符计算 
	 * @param str
	 * @param subSLength
	 * @return
	 */
	public static String subStr(String str, int subSLength) { 
		try {
			 if (TextUtils.isEmpty(str))  {
		           return "";  
			 } else if(getStrLength(str)<= subSLength){
				 return str;
			 }else{ 
		           int tempSubLength = subSLength;//截取字节数
		           String subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串  
		           int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字节长度 
		           //int subStrByetsL = subStr.getBytes().length;//截取子串的字节长度 
		           // 说明截取的字符串中包含有汉字  
		           while (subStrByetsL > tempSubLength){  
		        	   int subSLengthTemp = --subSLength;
		               subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);  
		               subStrByetsL = subStr.getBytes("GBK").length;
		               //subStrByetsL = subStr.getBytes().length;
		           }  
		           return subStr; 
		       }
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	   }
//	public static  String buildShareStr(Spot spot) {
//		String link = "http://www.ispied.com/l/" + spot.sid;
//		String format = AppHelper.getString(R.string.fashionshare_content);
//		String username = O2OApplication.mUserProfile.username;
//		String comments = String.format(format, username, spot.name, link);
//		return comments;
//	}
//	public static String buildShareStr(String desc,long sid){
//		StringBuilder result = new StringBuilder();
//		result.append(desc)
//		.append(AppHelper.getString(R.string.share_weibo_content))
//		.append("http://www.ispied.com/l/").append(sid);
//		return result.toString();
//	}
	
	
	/**
	 * drawable to Bitmap
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap (Drawable drawable) {
	    if (drawable instanceof BitmapDrawable) {
	        return ((BitmapDrawable)drawable).getBitmap();
	    }

	    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
	    Canvas canvas = new Canvas(bitmap); 
	    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
	    drawable.draw(canvas);

	    return bitmap;
	}
	/**
	 * 获取大图或小图的url
	 *  .jpg     480 * 360
	 *	_s.jpg   120 * 120 90 * 120
	 *	_l.jpg   640 * 480  
	 * @param isBig
	 * @return
	 */
	public static String imageUrlAdapt(String url,boolean isBig){
		if (TextUtils.isEmpty(url)) {
			return null;
		}
		if (url.endsWith(".jpg")) {
			if (isBig) {
				url = url.replaceAll(".jpg", "_l.jpg");
			}else{
				url = url.replaceAll(".jpg", "_s.jpg");
			}
			
		}
		return url;
	}
	public static boolean checkEmail(String email) {
		String regex = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(email);
		return matcher.find();
	}
	
	public  static boolean checkExpried(long expriesIn) {
		return  System.currentTimeMillis() > expriesIn-60*1000;
	}
	
	public static boolean checkMobile(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^1\\d{10}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
	
	public static boolean checkNull(String str) {
        if (str == null || str.length() == 0){
            return true;
        }
        str = str.trim();
        return str.length()==0;
    }
	
	
//	public static boolean isFollow(String userId){
//		if (O2OApplication.mFollowingIds == null) {
//			return false;
//		}
//		return O2OApplication.mFollowingIds.contains(userId);
//	}
	
	public static String getIMEI(){
		TelephonyManager TelephonyMgr = (TelephonyManager)BaseApplication.mContext.getSystemService(Context.TELEPHONY_SERVICE); 
		String imei = TelephonyMgr.getDeviceId();
		LogUtil.d("--imei==" + imei);
		if (TextUtils.isEmpty(imei)) {
			imei = getAndroidId();
		}
		return imei;
	}
	
	public static void call(String phoneNum){
		 Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ phoneNum));
		 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 BaseApplication.mContext.startActivity(intent);
	}
	
	public static void openUrl(String url){
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);        
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Uri content_url = Uri.parse(url);   
			intent.setData(content_url);  
			BaseApplication.mCurrentActivity.startActivity(intent);
		}catch(Exception e){
//			WebViewFragment.add(id, url, "");
		}
		
	}
	
	public static void dial(String phoneNum){
		if (TextUtils.isEmpty(phoneNum)) {
			BaseApplication.showToast("电话号码不能为空");
			return;
		}
		 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+ phoneNum));
		 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 BaseApplication.mContext.startActivity(intent);
	}
	public static void sms(String content,String toNum){
		 Uri uri = Uri.parse("smsto:" + toNum);        
         Intent it = new Intent(Intent.ACTION_SENDTO, uri);        
         it.putExtra("sms_body",content);        
		 BaseApplication.mContext.startActivity(it);
	}
	
	public static String formatDouble(double value,int length){
		BigDecimal each = new BigDecimal(value);
		each = each.setScale(length, BigDecimal.ROUND_HALF_UP);
		return each.toString();
	}
	
	public static String formatDouble(String value,int length){
		if (value == null) {
			return "0";
		}
		BigDecimal each = new BigDecimal(value);
		each = each.setScale(length, BigDecimal.ROUND_HALF_UP);
		return each.toString();
	}
	
	public static String getSubCategory(String categoryTree){
		if (!TextUtils.isEmpty(categoryTree)) {
			int index = categoryTree.lastIndexOf("_");
			int length = categoryTree.length();
			if (index > -1 && index < length) {
				return categoryTree.substring(index+1, length);
			}
		}
		return categoryTree;
	}
	
	final static String digits = "0123456789ABCDEF"; 
	public static String encode(String s) {  
        // Guess a bit bigger for encoded form  
        StringBuilder buf = new StringBuilder(s.length() + 16);  
        for (int i = 0; i < s.length(); i++) {  
            char ch = s.charAt(i);  
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')  
                    || (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$  
                buf.append(ch);  
            } else {  
                byte[] bytes = new String(new char[] { ch }).getBytes();  
                for (int j = 0; j < bytes.length; j++) {  
                    buf.append('%');  
                    buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));  
                    buf.append(digits.charAt(bytes[j] & 0xf));  
                }  
            }  
        }  
        return buf.toString();  
}  
	public static String buildLocationStr(Double lat,Double lon){
		JSONObject locationObj = new JSONObject();
		try {
			locationObj.put("longitude", String.valueOf(lon));
			locationObj.put("latitude", String.valueOf(lat));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return locationObj.toString();
	}
		
	public static String getDoubleStr(String doubleStr,int length){
		if (TextUtils.isEmpty(doubleStr)) {
			return "0";
		}
		BigDecimal bigDecimal= new BigDecimal(doubleStr); 
		bigDecimal= bigDecimal.setScale(length, BigDecimal.ROUND_HALF_UP); 
		return String.valueOf(bigDecimal.floatValue());
	}
	
	public static String getIntStr(String doubleStr){
		if (TextUtils.isEmpty(doubleStr)) {
			return "0";
		}
		BigDecimal bigDecimal= new BigDecimal(doubleStr); 
		bigDecimal= bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP); 
		return String.valueOf(bigDecimal.intValue());
	}
	
	public static Bitmap readBitMap(int resId){ 
		BitmapFactory.Options opt=new BitmapFactory.Options(); 
		opt.inPreferredConfig=Bitmap.Config.ARGB_8888; 
		opt.inPurgeable=true; 
		opt.inInputShareable=true; 
		//获取资源图片 
		InputStream is=BaseApplication.mContext.getResources().openRawResource(resId); 
		return BitmapFactory.decodeStream(is,null,opt); 
	}
	public static Bitmap readBitMap(String filePath){ 
		BitmapFactory.Options opt=new BitmapFactory.Options(); 
		opt.inPreferredConfig=Bitmap.Config.ARGB_8888; 
		opt.inPurgeable=true; 
		opt.inInputShareable=true; 
		//获取资源图片 
		return BitmapFactory.decodeFile(filePath,opt); 
		} 
	
	public static String getPinYin(String inputString) {  
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();  
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
//        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);  
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);  
        char[] input = inputString.trim().toCharArray();  
        StringBuffer output = new StringBuffer("");  
        try {  
            for (int i = 0; i < input.length; i++) {  
                if (Character.toString(input[i]).matches("[\u4E00-\u9FA5]+")) {  
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);  
                    System.out.println("temp.length==" + temp.length);
                    for (int j = 0; j < temp.length; j++) {
					System.out.println("value" + j + "==" + temp[j]);	
					}
                    output.append(temp[0]);  
                    output.append("");  
                } else  
                    output.append(Character.toString(input[i]));  
            }  
        } catch (BadHanyuPinyinOutputFormatCombination e) {  
            e.printStackTrace();  
        }  
        return output.toString();  
    }
	
	// 获取ApiKey
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true，unBind且成功时设置false
    public static boolean hasBind(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        String flag = sp.getString("bind_flag", "");
        if ("ok".equalsIgnoreCase(flag)) {
            return true;
        }
        return false;
    }

    public static void setBind(Context context, boolean flag) {
        String flagStr = "not";
        if (flag) {
            flagStr = "ok";
        }
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sp.edit();
        editor.putString("bind_flag", flagStr);
        editor.commit();
    }
    
    public boolean  isGpsOpen(){
        LocationManager lm = (LocationManager) BaseApplication.mContext.getSystemService(Context.LOCATION_SERVICE);
        boolean gpsStatus = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);//获得手机是不是设置了GPS开启状态true：gps开启，false：GPS未开启
        boolean networkStatus = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);//另一种Gpsprovider（Google网路地图）
       return gpsStatus || networkStatus ;
    }
    
	/**
	 * 获取UA信息
	 * 'HTTP_USER_AGENT' => '维?~V?~Q?线 2.1.0 rv:194 (iPhone; iPhone OS 8.1; en_GB)'
	 */
	public static String getUserAgent(){
		WebView webview;
		webview = new WebView(BaseApplication.mContext);
		webview.layout(0, 0, 0, 0);
		WebSettings settings = webview.getSettings();
		// Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; Galaxy Nexus
		// Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0
		String ua = settings.getUserAgentString();
		int begin = ua.indexOf('(');
		int end = ua.indexOf(')');
		String str = ua.substring(begin, end+1);
		StringBuffer result = new StringBuffer();
		result.append(BaseApplication.getResString(R.string.app_name))
		.append("  rv:")
		.append(getVersionCode())
		.append("  ")
		.append(str);
		return result.toString();
	}
	
	public static String getVersion(){//获取版本号  
		try {  
            PackageInfo pi=BaseApplication.mContext.getPackageManager().getPackageInfo(BaseApplication.mContext.getPackageName(), 0);  
            return pi.versionName;  
        } catch (NameNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return null;
        }  
    }  
 
	public static int getVersionCode() {  //获取版本号(内部识别号) 
	    try {  
	        PackageInfo pi=BaseApplication.mContext.getPackageManager().getPackageInfo(BaseApplication.mContext.getPackageName(), 0);  
	        return pi.versionCode;  
	    } catch (NameNotFoundException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	        return 0;  
	    }  
	}  
	

	public static String getAndroidId() {
		return android.provider.Settings.Secure.getString(
		BaseApplication.mContext.getContentResolver(),
		android.provider.Settings.Secure.ANDROID_ID);
	}

	public static String getSimSerialNumber() {

	    return ((TelephonyManager)BaseApplication.mContext.getSystemService(

	    Context.TELEPHONY_SERVICE)).getSimSerialNumber();

	}

	public static String getSerialNumber1() {
	    return android.os.Build.SERIAL;
	}
	
	/**
	 * 判断应用是否在前台运行
	 * @param context
	 * @return
	 */
	public static boolean isRunningForeground (Context context)  {  
	    ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);  
	    ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
	    String currentPackageName = cn.getPackageName();  
	    if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())){  
	        return true ;  
	    }  
	    return false ;  
	}  
	public static boolean responseSuccess(BaseResponse response){
		boolean result = false;
		if (response != null && response.getErr() == CONSTANT.NO_ERROR_STATUS) {
			result = true;
		}
		return result;
	}
	
	public static boolean checkUser(BaseResponse response){
		boolean result = false;
		//用户已停用或过期
		if (response != null && (response.getErr() == 44 || response.getErr() == 45 || response.getErr() == 46 || response.getErr() == 8 || response.getErr() == 18 || response.getErr() == 81)) {
			result = true;
			BaseApplication.showToast(response.getErrMsg());
		}
		return result;
	}
	
	public static List<String> readFileToList(Context context, String fileName) {
        List<String> fileContent = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            InputStreamReader is = new InputStreamReader(context.getAssets().open(fileName));
            reader = new BufferedReader(is);
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileContent.add(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException("IOException occurred. ", e);
                }
            }
        }
        return fileContent;
    }
	public static Bitmap resizeImage(byte[] bytes, int newHeight, int newWidth){  
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = false;
        Bitmap BitmapOrg = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt); 
        int width = BitmapOrg.getWidth();  
        int height = BitmapOrg.getHeight();  
        float scaleWidth = ((float) newWidth) / width;  
        float scaleHeight = ((float) newHeight) / height;  

        Matrix matrix = new Matrix();  
        matrix.postScale(scaleWidth, scaleHeight);  
        // if you want to rotate the Bitmap   
        // matrix.postRotate(45);   
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,  
                        height, matrix, true);  
        return resizedBitmap;  
    }
	
	/**
	 * 获取上传图片的存储路�?
	 * @return
	 */
	public static String getUploadPicturePath(){
		String path = null;
		if (hasSdCard()) {
			path = BaseApplication.mContext.getExternalFilesDir("").toString();
		}else{
			path = BaseApplication.mContext.getFilesDir().toString();
		}
		path += "/uploadImage/";
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
		return path;
	}
	public static void loveAnimator(View view){
	       AnimatorSet animatorSet = new AnimatorSet();  
	       ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX",1f,1.5f);  
	       scaleX.setDuration(200);  
	       ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f,1.5f);  
	       scaleY.setDuration(200); 
	       ObjectAnimator scaleXN = ObjectAnimator.ofFloat(view, "scaleX",1.5f,1.0f);  
	       scaleX.setDuration(200);  
	       ObjectAnimator scaleYN = ObjectAnimator.ofFloat(view, "scaleY",1.5f,1.0f);  
	       scaleY.setDuration(200); 
	       animatorSet.play(scaleXN).with(scaleYN);
	       animatorSet.play(scaleX).with(scaleY);
	       animatorSet.start();  
	   }  
	public static boolean isToday(String time){
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(Long.parseLong(time));
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int month = calendar.get(Calendar.MONTH);
		int year = calendar.get(Calendar.YEAR);
		
		Calendar today = Calendar.getInstance();
		int todayDay = today.get(Calendar.DAY_OF_MONTH);
		int todayMonth = today.get(Calendar.MONTH);
		int todayYear = today.get(Calendar.YEAR);
		return day == todayDay && month == todayMonth && year == todayYear;
	}
	
	public static boolean isRunnian(int year){
		if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
		    return true;
		}else{
			return false;
		}
	}
	public static int getDayCount(int year,int month){
		int day = 31;
		if (month == 2) {
			day = isRunnian(year)?29:28;
		}else if (month == 4 || month == 6|| month == 9 || month == 11) {
			day = 30;
		}
		return day;
	}
	
	public static int []  buildData(int min,int max){
		int length = max-min+1;
		int [] array  = new int[length];
		for (int i = 0; i < length; i++) {
			array[i] = min+i;
		}
		return array;
	}
	
	public static String buildCropUrl(int width,int height){
		return "?imageView2/1/w/"+ width + "/h/" + height;
	}
	
	static String shareEventId;
	static public void showShareDialog(int assoType,LinearLayout dialogView,final Dialog mShareDialog,LayoutInflater mInflater,final String mShareImg,final String title,final String content,final String shareUrl){
		switch (assoType) {
		case CONSTANT.ASSO_TYPE_ACTIVE:
			shareEventId = CONSTANT.EVENT_ID.ACTIVE_SHARE;
			break;
		case CONSTANT.ASSO_TYPE_WEIKE:
			shareEventId = CONSTANT.EVENT_ID.WEIKE_SHARE;
			break;
		case CONSTANT.ASSO_TYPE_COMMUNITY:
			shareEventId = CONSTANT.EVENT_ID.COMMUNITY_SHARE;
			break;
		default:
			break;
		}
		TextView qqIcon = (TextView) dialogView.findViewById(R.id.share_pop_qq);
		TextView qzoneIcon = (TextView) dialogView.findViewById(R.id.share_pop_qzone);
		TextView wechatIcon = (TextView) dialogView.findViewById(R.id.share_pop_wechat);
		TextView wechatTimeLineIcon = (TextView) dialogView.findViewById(R.id.share_pop_wechat_timeline);
		TextView weiboIcon = (TextView) dialogView.findViewById(R.id.share_pop_weibo);
		qqIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonUtil.umengEvent(shareEventId,CONSTANT.SHARE_EVENT_TYPE_QQ,CONSTANT.SHARE_EVENT_TYPE_QQ);
				mShareDialog.dismiss();
				WrapQQ.getInstance().shareToQQ(title,content, shareUrl,mShareImg, new IUiListener() {
					
					@Override
					public void onError(UiError arg0) {
						// TODO Auto-generated method stub
						BaseApplication.showToast(R.string.share_failed);
					}
					
					@Override
					public void onComplete(Object arg0) {
						// TODO Auto-generated method stub
						BaseApplication.showToast(R.string.share_success);
					}
					
					@Override
					public void onCancel() {
						// TODO Auto-generated method stub
					}
				});
			}
		});
		qzoneIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonUtil.umengEvent(shareEventId,CONSTANT.SHARE_EVENT_TYPE_QZONE,CONSTANT.SHARE_EVENT_TYPE_QZONE);
				mShareDialog.dismiss();
				ArrayList<String> imageUrls =  new ArrayList<String>();
				String imageUrl = mShareImg;
				if (TextUtils.isEmpty(imageUrl)) {
			    	imageUrl = CommonUtil.getLogoImagePath();
					if (TextUtils.isEmpty(imageUrl)) {
						imageUrl = CommonUtil.saveLogoImagePath();
					}
				}
				imageUrls.add(imageUrl);
				WrapQQ.getInstance().shareToQzone(title,content, shareUrl,imageUrls, new IUiListener() {
					
					@Override
					public void onError(UiError arg0) {
						// TODO Auto-generated method stub
						BaseApplication.showToast(R.string.share_failed);
					}
					
					@Override
					public void onComplete(Object arg0) {
						// TODO Auto-generated method stub
						BaseApplication.showToast(R.string.share_success);
					}
					
					@Override
					public void onCancel() {
						// TODO Auto-generated method stub
						
					}
				});
			}
		});
		wechatIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonUtil.umengEvent(shareEventId,CONSTANT.SHARE_EVENT_TYPE_WECHAT,CONSTANT.SHARE_EVENT_TYPE_WECHAT);
				mShareDialog.dismiss();
				if (TextUtils.isEmpty(mShareImg)) {
					Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.mContext.getResources(), R.drawable.logo);
					WrapWechat.getInstance().shareWebPageToWechat(title,content,shareUrl, bitmap, false);
				}else{
					HttpManager.getInstance().downLoadImage(mShareImg,new LoadImageViewResponse() {
						@Override
						public void loadFinish(Bitmap bitmap) {
							WrapWechat.getInstance().shareWebPageToWechat(title,content,shareUrl, bitmap, false);
						}
					});
				}
			}
		});
		wechatTimeLineIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonUtil.umengEvent(shareEventId,CONSTANT.SHARE_EVENT_TYPE_WECHAT_TIMELINE,CONSTANT.SHARE_EVENT_TYPE_WECHAT_TIMELINE);
				mShareDialog.dismiss();
				if (TextUtils.isEmpty(mShareImg)) {
					Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.mContext.getResources(), R.drawable.logo);
					WrapWechat.getInstance().shareWebPageToWechat(title,content,shareUrl, bitmap, true);
				}else{
					HttpManager.getInstance().downLoadImage(mShareImg,new LoadImageViewResponse() {
						@Override
						public void loadFinish(Bitmap bitmap) {
							WrapWechat.getInstance().shareWebPageToWechat(title,content,shareUrl, bitmap, true);
						}
					});
				}
			}
		});
		weiboIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
				CommonUtil.umengEvent(shareEventId,CONSTANT.SHARE_EVENT_TYPE_SINA,CONSTANT.SHARE_EVENT_TYPE_SINA);
				WrapSinaWeibo.getInstance().shareToWeibo(title,shareUrl,mShareImg);
			}
		});
		mShareDialog.show();
	}
	
	public static String getChannelValue(){
		ApplicationInfo appInfo = null;
		try {
			appInfo = BaseApplication.mContext.getPackageManager().getApplicationInfo(BaseApplication.mContext.getPackageName(),
					PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String channel = appInfo.metaData.getString("UMENG_CHANNEL");
		return channel;
	}

	public static void umengEvent(String eventId){
		MobclickAgent.onEvent(BaseApplication.mCurrentActivity,eventId);  
	}
	public static void umengEvent(String eventId,HashMap<String, String> map){
		MobclickAgent.onEvent(BaseApplication.mCurrentActivity,eventId, map);  
	}
	
	public static void umengEvent(String eventId,String key,String value){
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(key, value);
		MobclickAgent.onEvent(BaseApplication.mCurrentActivity,eventId, map);  
	}
	/**
	 * 半角转全角
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {  
		   char[] c = input.toCharArray();  
		   for (int i = 0; i< c.length; i++) {  
		       if (c[i] == 12288) {  
		         c[i] = (char) 32;  
		         continue;  
		       }
		       if (c[i]> 65280 && c[i]< 65375)  
		          c[i] = (char) (c[i] - 65248);  
		       }  
		   return new String(c);  
		}  
	
	
}
